package com.sky.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.sky.dto.DishDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.result.Result;
import com.sky.service.DishFlavorService;
import com.sky.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController("AdminDishController")
@RequestMapping("/admin/dish")
@Slf4j
@Api("菜品相关接口")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 菜品分页查询
     */
    @ApiOperation("菜品分页查询")
    @GetMapping("/page")
    public Result page(int page,int pageSize,String name,Integer status,Long categoryId){
        Page<Dish> pageInfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(name!=null,Dish::getName,name);
        lambdaQueryWrapper.eq(categoryId!=null,Dish::getCategoryId,categoryId);
        lambdaQueryWrapper.eq(status!=null,Dish::getStatus,status);
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo,lambdaQueryWrapper);
        return Result.success(pageInfo);
    }

    /**
     * 新增菜品
     * @return
     */
    @PostMapping
    @ApiOperation("新增菜品")
    public Result<String> save(@RequestBody DishDTO dishDTO){
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        Random random=new Random();
        Long dishId= (long) random.nextInt(1000000);
        dish.setId(dishId);
        if(flavors!=null){
            flavors=flavors.stream().map(item->{
                item.setDishId(dishId);
                return item;
            }).collect(Collectors.toList());
            dishFlavorService.saveBatch(flavors);
        }
        dishService.save(dish);

        //清理Redis缓存(清理当前添加菜品所对应的分类)
        String key="dish_"+ dishDTO.getCategoryId();
        redisTemplate.delete(key);

        return Result.success("添加成功") ;
    }

    /**
     * 根据id获取菜品
     */
    @ApiOperation("根据id获取菜品")
    @GetMapping("/{id}")
    public Result<DishDTO> getById(@PathVariable Long id){
        DishDTO dishDTO=new DishDTO();
        //获取dish信息
        Dish dish = dishService.getById(id);
        BeanUtils.copyProperties(dish,dishDTO);
        //获取dishFlavor信息
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper =new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> flavors = dishFlavorService.list(lambdaQueryWrapper);
        dishDTO.setFlavors(flavors);
        return Result.success(dishDTO);
    }

    /**
     * 修改菜品
     */
    @ApiOperation("修改菜品")
    @PutMapping
    public Result<String> update(@RequestBody DishDTO dishDTO){
        Dish dish =new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //更新dish表
        dishService.updateById(dish);
        //更新dishFlavor表
        Long dishId=dish.getId();
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
        dishFlavorService.remove(lambdaQueryWrapper);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors!=null){
            flavors=flavors.stream().map(item->{
                item.setDishId(dishId);
                return item;
            }).collect(Collectors.toList());
            dishFlavorService.saveBatch(flavors);
        }
        //清理缓存（所有的缓存，因为修改菜品的分类时很麻烦，所以全部删除）
        cleanCaChe("dish_*");
        return Result.success("修改成功");
    }

    /**
     * 菜品的起售、停售
     */
    @ApiOperation("菜品的起售、停售")
    @PostMapping("/status/{status}")
    public Result<String> changeStatus(@PathVariable Integer status,Long id){
        Dish dish = dishService.getById(id);
        dish.setStatus(status);
        dishService.updateById(dish);
        //清理缓存，删除对应的缓存
        String key="dish_"+dish.getCategoryId();
        redisTemplate.delete(key);
        return Result.success("修改成功");
    }

    /**
     * 根据ids删除菜品
     */
    @ApiOperation("根据ids删除菜品")
    @DeleteMapping
    public Result<String> deleteByIds(Long[] ids){
        ArrayList<Long> list=new ArrayList<>(ids.length);
        Collections.addAll(list,ids);
        //删除dish
        dishService.removeByIds(list);
        //删除dish对应的dishFlavor
        list.stream().map(id->{
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,id);
            dishFlavorService.remove(lambdaQueryWrapper);
            return id;
        }).collect(Collectors.toList());
        //清理缓存（清理所有菜品缓存）
        cleanCaChe("dish_*");
        return Result.success("批量删除成功");
    }

    /**
     * 根据categoryId查询菜品
     */
    @GetMapping("/list")
    public Result<List<Dish>> getByCategoryId(Long categoryId,String name){
        LambdaQueryWrapper<Dish> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(categoryId!=null,Dish::getCategoryId,categoryId);
        lambdaQueryWrapper.like(name!=null,Dish::getName,name);
        List<Dish> list = dishService.list(lambdaQueryWrapper);
        return Result.success(list);
    }

    /**
     * 清除所有缓存
     * @param pattern
     */
    private void cleanCaChe(String pattern){
        Set keys = redisTemplate.keys(pattern);
        if(keys!=null){
            redisTemplate.delete(keys);
        }
    }

}
